window.onload = function () {
    let currentPage = 1;
    const itemsPerPage = 10;
    let totalItems = 0;
    const content = document.getElementById('content');
    const loadingIndicator = document.getElementById('loading');
    let isLoading = false;

    function fetchData() {
        return new Promise((resolve) => {
            setTimeout(() => {
                const data = [];
                for (let i = 0; i < itemsPerPage; i++) {
                    data.push(`项目 ${totalItems + i + 1}`);
                }
                resolve(data);
            }, 1000);
        });
    }

    async function loadMore() {
        if (isLoading) return;

        isLoading = true;
        loadingIndicator.style.display = 'block';

        try {
            const data = await fetchData();

            data.forEach(item => {
                const itemElement = document.createElement('div');
                itemElement.className = 'item';
                itemElement.textContent = item;
                content.appendChild(itemElement);
            });

            totalItems += data.length;
            currentPage++;

            // 模拟数据结束条件
            if (currentPage > 5) {
                window.removeEventListener('scroll', checkScroll);
                loadingIndicator.textContent = '已加载全部内容';
            }
        } finally {
            isLoading = false;
            loadingIndicator.style.display = 'none';
        }
    }

    function checkScroll() {
        const {
            scrollTop,
            clientHeight,
            scrollHeight
        } = document.documentElement;
        if (scrollTop + clientHeight >= scrollHeight - 100) {
            loadMore();
        }
    }
    //闭包加定时器,避免频繁
    function debounce(func, wait) {
        let timeout;
        return function () {
            const context = this,
                args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }

    loadMore();
    window.addEventListener('scroll', debounce(checkScroll, 200));
};